# -*- coding: utf-8 -*-

"""
DateTime   : 2021/04/06 11:19
Author     : ZhangYafei
Description: 
"""
import os

import requests
from prettytable import PrettyTable
from tqdm import tqdm

image_type_info = {
    0: '最新壁纸', 6: '美女模特', 30: '爱情美图', 9: '风景大片',
    36: '4K专区', 15: '小清新', 26: '动漫卡通', 11: '明星风尚',
    14: '萌宠动物', 5: '游戏壁纸', 12: '汽车天下', 10: '炫酷时尚',
    29: '月历壁纸', 7: '景视剧照', 35: '文字控', 13: '节日美图',
    22: '军事天地', 16: '劲爆体育', 18: 'BABY秀'
}

def init_tips_info():
    table = PrettyTable(['序号1', '壁纸分类1', '序号2', '壁纸分类2'])
    row = []
    for index, key in enumerate(image_type_info, start=1):
        row.extend([key, image_type_info[key]])
        if len(row) == 4:
            table.add_row(row)
            row.clear()
            continue
        if index == len(image_type_info):
            row.extend(['-', '-'])
            table.add_row(row)
    print(table)

def main(image_type: int, start: int = 1, count: int = 50):
    url = 'https://bird.ioliu.cn/v2'

    if image_type == 0:
        params = {'url': f'http://wallpaper.apc.360.cn/index.php?c=WallPaper&start={start}&count={count}&from=360chrome&a=getAppsByOrder&order=create_time'}
    else:
        params = {'url': f'http://wallpaper.apc.360.cn/index.php?c=WallPaper&start={start}&count={count}&from=360chrome&a=getAppsByCategory&cid={image_type}'}

    # 图片文件夹分类
    image_type_desc = image_type_info[image_type]
    if not os.path.exists(f'images/{image_type_desc}'):
        os.makedirs(f'images/{image_type_desc}')

    # 发送请求
    response = requests.get(url=url, params=params)
    result = response.json()

    task_progress = tqdm(result['data'], ncols=100)

    for index, image_info in enumerate(task_progress, start=1):
        task_progress.set_description(f"正在下载第 {index} 张图片")
        uid = image_info['id']
        image_url = image_info['url']
        tags = image_info['tag'].replace('_category_', '').replace('_全部_', '').strip('_ ').replace(' ', '')
        size = image_info['resolution'].replace('x', '_')
        filepath = f'images/{image_type_info[image_type]}/{tags}_{uid}_{size}.jpg'
        response = requests.get(image_url)
        with open(filepath, mode='wb') as f:
            f.write(response.content)
        # print(f'{image_url} {filepath} 下载成功')

    print(f'所有图片下载完成!')

init_tips_info()

while True:
    image_type = input('请选择下载的壁纸分类(序号,默认回车为0) >>  ')
    if image_type:
        if not image_type.isdecimal() or int(image_type) not in image_type_info:
            print('您输入的分类序号有误，请重新确认后输入')
            continue
        else:
            image_type = int(image_type)
    else:
        image_type = 0

    break
while True:
    count = input('请输入下载数量（整数，默认为50）>> ')
    if count:
        if not count.isdecimal():
            print('您输入的数量有误，必须为整数，请重新输入')
            continue
        else:
            count = int(count)
    else:
        count = 20
    break

main(image_type=image_type, count=count)